const myUtils = require("../../utils/myUtils");
let db;
let ui;
// const ui={
//   openId:500
// }
Page({
  data: {
    questions: [],
    answer: [], //用户回答的内容
    dbData: {}, //提交到数据库的数据
    userInfo:null,
    initComplete:false,
    date:{},
    checked:null,
  },
  onShow: async function () {
    this.setData({
      initComplete:false
    });
    const time = await myUtils.getTime();
    const date = {
      day: time.day,
      // day: 21,

      month: time.month,
      year: time.year
    };
    this.setData({
      date:date
    });
    db = wx.cloud.database();
    ui = wx.getStorageSync("userInfo");
    if(ui==null||ui.openid==null){
      wx.switchTab({
        url: '/pages/me/me',
      })
      await wx.showModal({
        title: '提示',
        content: '请先登录!',
        showCancel: false,
        confirmText: '知道了',
      });
      return;
    }
    var res=await wx.cloud.callFunction({
      name: "get_user_info",
      data: {
        openId:ui.openid
        // openId:123
      },
    });
    console.log(res);
    if(res.result==null){
      wx.switchTab({
        url: '/pages/me/me',
      })
      await wx.showModal({
        title: '提示',
        content: '请先填写个人信息!',
        showCancel: false,
        confirmText: '知道了',
      });
      return;
    }
    this.setData({
      userInfo:res.result
    });
    console.log(this.data.userInfo);

    await this.getQuestions();
    await this.initAnswer();
    await this.echoAnswer();
    this.setData({
      initComplete:true
    });
  },
  echoAnswer:async function(){
    let res=await wx.cloud.callFunction({
      name:"get_record_by_condition",
      data:{
        collection:"answer_daily",
        condition:{
          data:{
            openId:ui.openid
          },
          date:this.data.date
          // date:123
        },
      }
    });

    console.log(res);
    if(res.result.data.length===0){
      return;
    }
    let datas=res.result.data[0].data;
    console.log("datas:",datas);
    let userAns;
    for(let data of datas){
      if(data.openId===ui.openid){
        userAns=data;
        break;
      }
    }
    console.log(userAns);
    let hisAnswers=userAns.answer;
    let answers=this.data.answer;
    console.log(answers);
    for(let hisAns of hisAnswers){
      for(let ans of answers){
        if(ans.questionName===hisAns.questionName){
          ans.value=hisAns.value;
          break;
        }
      }
    }
    console.log(answers);
    this.setData({
      answer:answers
    });
    //单选题的回显
    let checked=[];
    for(let ques of this.data.questions){
      let row=[];
      console.log(ques);
      if(ques.type!=="radio"){//不是单选，则跳过
        checked.push(null);
        continue;
      }
      for(let ans of answers){

        if(ques.question===ans.questionName){
          
          for(let index in ques.options){
            if(ques.options[index]===ans.value){
              row.push("checked");
            }
            else{
              row.push("");
            }
          }
          
          break;
        }
      }
      checked.push(row);
    }
    console.log(checked);
    this.setData({
      checked:checked
    });

  },
  handleSubmit: async function () {
    if (!this.checkComplete()) {
      wx.showModal({
        title: '提示',
        content: '请填写所有问题!',
        showCancel: false,
        confirmText: '知道了',
      }).then(res => {
        if (res.confirm) {
          console.log('用户点击知道了');
        }
      });
      return;
    } else {
      
      

      const _ = db.command;
      const date=this.data.date;
      const dateNum = parseInt(`${date.year}${String(date.month).padStart(2, '0')}${String(date.day).padStart(2, '0')}`, 10);
      //拼接数据准备上传
      this.setData({
        dbData: {
          openId: ui.openid,
          // openId: 500,
          answer: this.data.answer,
          time: this.data.time
        }
      });

      db.collection('answer_daily')
        .where({
          date: date
        }).get().then(res => {
          console.log(res);
          console.log(res.data.length);
          if (res.data.length == 0) {
            db.collection('answer_daily')
              .add({
                data: {
                  date: date,
                  data: [this.data.dbData],
                  dateNum:dateNum
                }
              }).then(res => {
                console.log("添加了今天第一份数据");
              })
          } else {
            let flag = false;
            let ansIndex;
            for (let index in res.data[0].data) {
              if (res.data[0].data[index].openId === ui.openid) {
                flag = true;
                ansIndex = index;
                break;
              }
            }
            if (flag) { //如果有相同的openId，则覆盖
              db.collection('answer_daily')
                .where({
                  data: {
                    openId: ui.openid
                  },
                  date: date
                }).update({
                  data: {
                    [`data.${ansIndex}`]: this.data.dbData
                  }
                }).then(res => {
                  console.log("更新成功");
                })
            } else { //如果没有相同的openId，则插入
              db.collection('answer_daily')
                .where({
                  date: date
                }).update({
                  data: {
                    data: _.push(this.data.dbData)
                  }
                }).then(res => {
                  console.log("插入成功");
                })
            }
          }
        });
      this.submitSuccess();

    }
  },
  submitSuccess(){
    wx.showModal({
      title: '提交成功',
      content: '您的问卷已提交成功!',
      showCancel: false,
      confirmText: '知道了',
    }).then(res => {
      if (res.confirm) {
        console.log('用户点击知道了');
      }
    });
  },
  initAnswer:async function() {
    let answer = [];
    for (let ques of this.data.questions) {
      let obj={
        questionId: ques._id,
        questionName: ques.question,
        type:ques.type,
        value: null
      };
      if(obj.type==="slider"){
        obj.value=0;
      }
      answer.push(obj);
    }
    this.setData({
      answer: answer
    });
    // console.log(this.data.answer);
  },
  getQuestions:async function() {
    let res=await wx.cloud.callFunction({
      name: "get_question",
      data: {
        questionName: "question_daily",
      },
    })
    this.setData({
      questions: res.result.data
    });
  },
  onSliderChange(e) {
    const question_id = e.currentTarget.dataset.question_id;
    const sliderValue = e.detail.value;

    console.log(question_id);


    let answer = this.data.answer;

    for (let item of answer) {
      if (item.questionId == question_id) {
        item.value = sliderValue;
        break;
      }
    }
    this.setData({
      answer: answer
    })
    console.log(this.data.answer);
  },
  onInputChange(e) {
    const question_id = e.currentTarget.dataset.question_id;
    const value = e.detail.value;

    console.log(question_id);


    let answer = this.data.answer;

    for (let item of answer) {
      if (item.questionId == question_id) {
        item.value = value;
        break;
      }
    }
    this.setData({
      answer: answer
    })
    console.log(this.data.answer);
  },
  onRadioChange(e) {
    const question_id = e.currentTarget.dataset.question_id;
    const value = e.detail.value;
    const options=e.currentTarget.dataset.question_options;
    console.log(question_id);


    let answer = this.data.answer;

    for (let item of answer) {
      if (item.questionId == question_id) {
        // item.value = value;
        item.value=options[value];
        break;
      }
    }
    this.setData({
      answer: answer
    })
    console.log(this.data.answer);
  },
  onAddressChange(e) {
    const question_id = e.currentTarget.dataset.question_id;
    const value = e.detail.value;

    console.log(question_id);


    let answer = this.data.answer;

    for (let item of answer) {
      if (item.questionId == question_id) {
        item.value = value;
        break;
      }
    }
    this.setData({
      answer: answer
    })
    console.log(this.data.answer);
  },

  checkComplete() {
    for (let item of this.data.answer) {
      if (item.value == null) {
        return false;
      }
    }
    return true;
  }

})